#include "tools.h"
#include "myinet.h"
#include <stdio.h>

int
main(int argc, char** argv){

    if (argc < 3){
        fprintf(stderr, "usage: %s <ip address> <port number>", argv[0]);
        exit(-1);
    }
    int sockfd;
    char buf[1024] = {0};
    int portNumber = atoi(argv[2]);

    // get ip address
    struct in_addr ip_addr;
    if (get_in_addr_by_name_or_ip(argv[1], &ip_addr) == -1){
        error_exit(0, "invalid host address");
    }

    // 目标地址
    struct sockaddr_in addr = get_sockaddr_in(portNumber, ip_addr);

    // 创建套接字
    info("connecting to %s:%d", inet_ntoa(addr.sin_addr), portNumber);
    sockfd = connectTo(ip_addr, portNumber, SOCK_STREAM);

    if (sockfd < 0) {
        error_exit("connectTo", 0);
    }
    info("connected to %s:%d", inet_ntoa(addr.sin_addr), portNumber);

    // send one byte
    write(sockfd, "a", 1);

    if (sockfd < 0){
        error_exit("connectTo", "error connecting to target");
    }

    // 接收数据
    int size = 0;
    if ((size = read(sockfd, buf, sizeof(buf))) < 0){
        error_exit("read", "error receiving message");
    }

    info("get message: %s", buf);
    close(sockfd);

    return 0;
}
